/**
 * 添加和详情表单
 */
import React, { Component } from 'react';
import { Form, Input, Select, Row, Col, Icon, Tooltip, Button, message, Upload } from 'antd';
import moment from 'moment';
import { pwdExp, mobileExp } from '../../utils/regExp';
import { WxForm } from '../setting/wxForm';
import userService from '../../services/sysUser';
import { bindingAccountList, bindAccount } from '../../services/agent';
import { operatorBindingAccountList, operatorBindAccount } from '../../services/operator';
import { isSuccess } from '../../configs/error';
import { connect } from 'dva';

const FormItem = Form.Item;
const Option = Select.Option;

const formItemLayout = {
	labelCol: {
		span: 6,
	},
	wrapperCol: {
		span: 14,
	},
};

const styles = {
	row: {
		borderTop: '1px solid #ccc',
		padding: '8px'
	},
	title: {
		fontSize: '15px',
		marginBottom: '1em'
	},
	icon: {
		marginLeft: '5px'
	},
	uploadPreview: {
		width: '100px',
		height: '100px',
		border: '1px dashed rgba(0,0,0,0.2)',
		textAlign: 'center',
		lineHeight: '100px',
		fontSize: '40px',
		color: '#909090',
		cursor: 'pointer',
	},
	image: {
		width: '100%',
		height: '100%',
	},
};

function imgUrl(img, callback) {

}

function beforeUpload(file) {
	const isJPG = file.type === 'image/jpeg';
	if (!isJPG) {
		message.error('You can only upload JPG file!');
	}
	const isLt2M = file.size / 1024 / 1024 < 2;
	if (!isLt2M) {
		message.error('Image must smaller than 2MB!');
	}
	return isJPG && isLt2M;
}

@connect(({ app }) => ({ app }))
class BaseForm extends WxForm {
	state = {
		recorded: 0,
		hasChangeBindingAccount: false, // 是否点击更换账号按钮
		accountList: [], // 未绑定账号列表
		userError: '',
		userId: '',
	}

	async componentWillMount() {
		// const { source } = this.props;
		// let res = {};
		// if (source) {
		// 	res = await operatorBindingAccountList({});
		// 	if (isSuccess(res)) {
		// 		this.setState({ accountList: res.data });
		// 	}
		// } else {
		// 	res = await bindingAccountList({});
		// 	if (isSuccess(res)) {
		// 		this.setState({ accountList: res.data });
		// 	}
		// }
	}

	componentDidMount() {
		const { item } = this.props;
		item.roleIds ? this.ruleChange(item.roleIds[0]) : null;
	}

	componentWillReceiveProps(nextProps) {
		const { item: { shareBenefitType, sysLogo } } = nextProps;
		shareBenefitType ? this.setState({ recorded: shareBenefitType }) : null;
		if (sysLogo !== this.props.item.sysLogo && sysLogo) {
			this.setState({ avatarUrl: `/${sysLogo}` });
		}
	}

	componentDidUpdate(prevProps) {
		const { item } = this.props;
		if (prevProps.item !== item && item.roleIds) this.ruleChange(item.roleIds[0]);
	}

	ruleChange = id => {
		const { roles } = this.props;
		const target = roles.find(r => r.id === id);
		target ? this.setState({ recorded: target.shareBenefitType }) : null;
	}

	pswValidator = (rule, value, callback) => {
		const { item } = this.props;
		if (item.password === value || pwdExp.exp.test(value)) callback();
		else callback(true);
	}

	changeBindingAccount = () => {
		this.setState(prevState => ({
			hasChangeBindingAccount: !prevState.hasChangeBindingAccount,
		}));
	}

	onAvatarChange = (file) => {
		// beforeUpload(file);
		const { form: { setFieldsValue } } = this.props;
		const reader = new FileReader();
		reader.addEventListener('load', async () => {
			this.isUpload = true;
			const res = await userService.uploadLogo(file);
			if (isSuccess(res)) {
				this.setState({ avatarUrl: `/${res.data}` });
				setFieldsValue({ sysLogo: res.data });
			}
		});
		reader.readAsDataURL(file);
	}

	bindAccount = async () => {
		const { form: { getFieldValue }, agentId, operatorID, source } = this.props;
		const { accountList } = this.state;
		const bindAccountId = getFieldValue('bindAccount');
		if (!bindAccountId) {
			message.warn('请先选择要绑定的账号!');
			return;
		}
		let res = {};
		if (source === 'operator') {
			res = await operatorBindAccount({
				id: operatorID,
				bindingAccountId: bindAccountId,
				bindingExistAccount: 1,
			});
		} else {
			res = await bindAccount({
				id: agentId,
				bindingAccountId: bindAccountId,
				bindingExistAccount: 1,
			});
		}
		if (isSuccess(res)) {
			message.success('更换绑定账号成功!');
			this.setState({
				hasChangeBindingAccount: false,
				changedAccountName: accountList.filter(a => a.id === bindAccountId).map(a => a.username),
			});
		}
	}
  bindProduct = (pId) => {
    const {form,products} = this.props;
    const {getFieldsValue, setFieldsValue, getFieldDecorator} = form;
    const fields = getFieldsValue();
    for(let key in products) {
      if(products[key].id === pId) {
        fields.productId = products[key].id
        fields.productName = products[key].name
        fields.productKey = products[key].gizwitsProductKey
        break
      }
    }
    // fields[key] = oValue;
    setFieldsValue(fields);
  }

	render() {
		const { item = {}, roles, products, mode, app: { user: { isAdmin } } } = this.props;
		const { recorded, hasChangeBindingAccount, accountList, userError, userId, changedAccountName, avatarUrl } = this.state;
		const { getFieldDecorator } = this;
		const ext = item.ext || {};
		return (
			<Form layout="horizontal">
				<Row gutter={16}>
					{
						mode !== 'wx' ? [
							<Col span={12}><FormItem label="账号" hasFeedback {...formItemLayout}>
								{getFieldDecorator('username', {
									initialValue: item.username,
									rules: [
										{
											required: true,
											message: '请输入登录账号!',
										},
										{
											pattern: /^[a-zA-Z0-9_]{5,18}$/,
											message: '请输入5-18个字符（只能包含英文字母、数字、“_”（下划线））'
										}
									],
								})(<Input disabled={!!item.id} placeholder="请输入登录账号" />)}
							</FormItem></Col>,
							!item.id ? <Col span={12}><FormItem label="密码" hasFeedback {...formItemLayout}>
								{getFieldDecorator('password', {
									initialValue: item.password,
									rules: [
										{
											required: true,
											message: '请输入密码!',
										},
										{
											validator: this.pswValidator,
											message: pwdExp.des
										}
									],
								})(<Input prefix={<Icon type="lock" style={{ fontSize: 13 }} />} type="password" placeholder="请输入密码" />)}
							</FormItem></Col> : null,
							<Col span={12}><FormItem label="所属角色" hasFeedback {...formItemLayout}>
								{getFieldDecorator('roleIds', {
									initialValue: item.roleIds ? item.roleIds[0] : null,
									rules: [
										{
											required: true,
											message: '请选择角色!',
										},
									]
								})(<Select onChange={this.ruleChange}>{roles.map(r => <Option value={r.id}>{r.roleName}</Option>)}</Select>)}
							</FormItem></Col>,
              <Col span={12}><FormItem label="产品名称" hasFeedback {...formItemLayout}>
								{getFieldDecorator('productId', {
									initialValue: item.productId || null,
									rules: [
										{
											required: false,
											message: '请选择产品!',
										},
									]
								})(<Select onChange={this.bindProduct}>{products.map(p => <Option value={p.id}>{p.name}</Option>)}</Select>)}
							</FormItem></Col>,
              <Col span={12}><FormItem label="产品Id" hasFeedback {...formItemLayout}>
                {getFieldDecorator('productName', {
                  initialValue: item.productName || null,
                  rules: [
                    {
                      required: false,
                      message: '请选择产品Name!',
                    },
                  ]
                })(<Select onChange={this.bindProduct} disabled>{products.map(p => <Option value={p.name}>{p.id}</Option>)}</Select>)}
              </FormItem></Col>,
              <Col span={12}><FormItem label="产品Key" hasFeedback {...formItemLayout}>
                {getFieldDecorator('productKey', {
                  initialValue: item.productKey || null,
                  rules: [
                    {
                      required: false,
                      message: '请选择产品Key!',
                    },
                  ]
                })(<Input disabled/>)}
              </FormItem></Col>,
							<Col span={12}><FormItem label="昵称" hasFeedback {...formItemLayout}>
								{getFieldDecorator('nickName', {
									initialValue: item.nickName,
									rules: [
										{
											pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]{0,20}$/,
											message: '最多输入20个字符，只能输入中文、数字或英文字母'
										}
									]
								})(<Input placeholder="请输入用户昵称" />)}
							</FormItem></Col>,
							<Col span={12} style={{ maxHeight: 56 }}><FormItem label="手机" hasFeedback {...formItemLayout}>
								{getFieldDecorator('mobile', {
									initialValue: item.mobile,
									rules: [
										{
											required: true,
											pattern: mobileExp.exp,
											message: mobileExp.des,
										},
									],
								})(<Input placeholder="请输入手机号" />)}
							</FormItem></Col>,
							<Col span={12}><FormItem label="状态" hasFeedback {...formItemLayout}>
								{getFieldDecorator('isEnable', {
									initialValue: item.isEnable,
									rules: [
										{
											required: true,
											message: '请选择状态!',
										},
									]
								})(<Select ><Option value={1}>启用</Option><Option value={0}>禁用</Option></Select>)}
							</FormItem></Col>,
							// isAdmin ? <Col span={12}><FormItem label="绑定微信openid" hasFeedback {...formItemLayout}>
							// 	{getFieldDecorator('ext_wxOpenId', {
							// 		initialValue: ext.wxOpenId
							// 	})(<Input placeholder="请输入微信openid" />)}
							// </FormItem></Col> : null,
							// isAdmin ? <Col span={12}><FormItem label="绑定模板id" hasFeedback {...formItemLayout}>
							// 	{getFieldDecorator('ext_wxTemplateId', {
							// 		initialValue: ext.wxTemplateId
							// 	})(<Input placeholder="请输入模板id" />)}
							// </FormItem></Col> : null,
							isAdmin ? <Col span={12}><FormItem label="系统名称" hasFeedback {...formItemLayout}>
								{getFieldDecorator('sysName', {
									initialValue: item.sysName
								})(<Input placeholder="请输入系统名称" />)}
							</FormItem></Col> : null,
							// isAdmin ? <Col span={12}>

							// 	<FormItem label="系统logo" hasFeedback {...formItemLayout}>
							// 		{getFieldDecorator('sysLogo', { initialValue: item.sysLogo })(<Input style={{ display: 'none' }} />)}
							// 		<Upload beforeUpload={this.onAvatarChange} showUploadList={false} customRequest={() => { }}>
							// 			<div style={styles.uploadPreview}>
							// 				{avatarUrl ? (<img src={avatarUrl} style={styles.image} />) : <Icon type="plus" />}
							// 			</div>
							// 			<p style={{ paddingTop: '10' }}>
							// 				建议选择300*200尺寸的图片，类型：jpg、png
							// 			</p>
							// 		</Upload>
							// 	</FormItem>
							// </Col> : null
						] : [
								<Col span={12}><FormItem label="绑定账号" {...formItemLayout} >
									{!hasChangeBindingAccount
										? (changedAccountName || item.username) :
										getFieldDecorator('bindAccount', {
										})(
											<Select value={userId} style={{ width: 200 }} onChange={(selId) => this.setState({ userId: selId, userError: '' })}>
												{accountList.map(u => <Option value={u.id} key={u.id}>{u.username}</Option>)}
											</Select>
										)
									}
									{/* 暂时屏蔽按钮 */}
									{/* < Button
										type="primary"
										size="small" style={{ marginLeft: '1em' }}
										onClick={this.changeBindingAccount}
									>
										{!hasChangeBindingAccount ? '更换账号' : '取消'}
									</Button> */}
									{hasChangeBindingAccount && < Button
										type="primary"
										size="small" style={{ marginLeft: '1em' }}
										onClick={this.bindAccount}
									>
										确定
									</Button>}
								</FormItem></Col>,
								<Col span={12}><FormItem label="所属角色" hasFeedback {...formItemLayout}>
									{item.roleName}
								</FormItem></Col>,
								<Col span={12}><FormItem label="昵称" hasFeedback {...formItemLayout}>
									{item.nickName}
								</FormItem></Col>,
								<Col span={12}><FormItem label="手机号" hasFeedback {...formItemLayout}>
									{item.mobile}
								</FormItem></Col>,
								<Col span={12}><FormItem label="账号状态" hasFeedback {...formItemLayout}>
									{item.statusDesc}
								</FormItem></Col>
							]
					}
					{
						item.id ? [
							<Col span={12}><FormItem label="创建时间" hasFeedback {...formItemLayout}>
								{moment(item.ctime).format('YYYY-MM-DD HH:mm:ss')}
							</FormItem></Col>,
							<Col span={12}><FormItem label="修改时间" hasFeedback {...formItemLayout}>
								{moment(item.utime).format('YYYY-MM-DD HH:mm:ss')}
							</FormItem></Col>
						] : null
					}
				</Row>
				{/*{*/}
					{/*recorded === 2 || recorded[0] === 2 ?*/}
						{/*<Row style={styles.row}>*/}
							{/*<Col span={24} style={styles.title}>*/}
								{/*绑定入账账号*/}
							{/*<Tooltip title={'绑定入账账号'}>*/}
									{/*<Icon type="question-circle-o" style={styles.icon} />*/}
								{/*</Tooltip>*/}
							{/*</Col>*/}
							{/*<Col span={12}><FormItem label="微信验证:" hasFeedback {...formItemLayout}>*/}
								{/*{getFieldDecorator('ext_wxToken', {*/}
									{/*initialValue: ext.wxToken*/}
								{/*})(<Input placeholder="请输入微信验证" />)}*/}
							{/*</FormItem></Col>*/}
							{/*<Col span={12}><FormItem label="微信ID" hasFeedback {...formItemLayout}>*/}
								{/*{getFieldDecorator('ext_wxId', {*/}
									{/*initialValue: ext.wxId*/}
								{/*})(<Input placeholder="请输入微信ID" />)}*/}
							{/*</FormItem></Col>*/}
							{/*<Col span={12}><FormItem label="微信appid" hasFeedback {...formItemLayout}>*/}
								{/*{getFieldDecorator('ext_wxAppid', {*/}
									{/*initialValue: ext.wxAppid*/}
								{/*})(<Input placeholder="请输入微信appid" />)}*/}
							{/*</FormItem></Col>*/}
							{/*<Col span={12}><FormItem label="微信appsecret" hasFeedback {...formItemLayout}>*/}
								{/*{getFieldDecorator('ext_wxAppSecret', {*/}
									{/*initialValue: ext.wxAppSecret*/}
								{/*})(<Input placeholder="请输入微信appsecret" />)}*/}
							{/*</FormItem></Col>*/}
							{/*<Col span={12}><FormItem label="关注推送消息" hasFeedback {...formItemLayout}>*/}
								{/*{getFieldDecorator('ext_wxSubscribeMsg', {*/}
									{/*initialValue: ext.wxSubscribeMsg*/}
								{/*})(<Input placeholder="请输入关注推送消息" />)}*/}
							{/*</FormItem></Col>*/}
							{/*<Col span={12}><FormItem label="微信支付消息体" hasFeedback {...formItemLayout}>*/}
								{/*{getFieldDecorator('ext_wxPayBody', {*/}
									{/*initialValue: ext.wxPayBody*/}
								{/*})(<Input placeholder="请输入微信支付消息体" />)}*/}
							{/*</FormItem></Col>*/}
							{/*<Col span={12}><FormItem label="微信支付商户号" hasFeedback {...formItemLayout}>*/}
								{/*{getFieldDecorator('ext_wxParenterId', {*/}
									{/*initialValue: ext.wxParenterId*/}
								{/*})(<Input placeholder="请输入微信支付商户号" />)}*/}
							{/*</FormItem></Col>*/}
							{/*<Col span={12}><FormItem label="微信支付商户key" hasFeedback {...formItemLayout}>*/}
								{/*{getFieldDecorator('ext_wxPartnerSecret', {*/}
									{/*initialValue: ext.wxPartnerSecret*/}
								{/*})(<Input placeholder="请输入微信支付商户key" />)}*/}
							{/*</FormItem></Col>*/}
						{/*</Row> : null*/}
				{/*}*/}
				{/*{*/}
					{/*recorded === 3 || recorded[0] === 3 ?*/}
						{/*<Row style={styles.row}>*/}
							{/*<Col span={24} style={styles.title}>*/}
								{/*绑定收款账号*/}
							{/*<Tooltip title={'绑定收款账号'}>*/}
									{/*<Icon type="question-circle-o" style={styles.icon} />*/}
								{/*</Tooltip>*/}
							{/*</Col>*/}
							{/*<Col span={12}><FormItem label="收款微信openid" hasFeedback {...formItemLayout}>*/}
								{/*{getFieldDecorator('ext_receiverOpenId', {*/}
									{/*initialValue: ext.receiverOpenId*/}
								{/*})(<Input placeholder="请输入收款微信openid" />)}*/}
							{/*</FormItem></Col>*/}
							{/*<Col span={12}><FormItem label="收款微信实名" hasFeedback {...formItemLayout}>*/}
								{/*{getFieldDecorator('ext_receiverWxName', {*/}
									{/*initialValue: ext.receiverWxName*/}
								{/*})(<Input placeholder="请输入收款微信实名" />)}*/}
							{/*</FormItem></Col>*/}
						{/*</Row> : null*/}
				{/*}*/}
				{/*{*/}
					{/*recorded === 4 || recorded[0] === 4 ?*/}
						{/*<Row style={styles.row}>*/}
							{/*<Col span={24} style={styles.title}>*/}
								{/*绑定缴费微信openid*/}
							{/*<Tooltip title="缴费微信openid">*/}
								{/*<Icon type="question-circle-o" style={styles.icon} />*/}
							{/*</Tooltip>*/}
							{/*</Col>*/}
							{/*<Col span={12}><FormItem label="缴费微信openid" hasFeedback {...formItemLayout}>*/}
								{/*{getFieldDecorator('ext_receiverOpenId', {*/}
									{/*initialValue: ext.receiverOpenId*/}
								{/*})(<Input placeholder="请输入缴费微信openid" />)}*/}
							{/*</FormItem></Col>*/}
							{/*<Col span={12}><FormItem label="缴费微信实名" hasFeedback {...formItemLayout}>*/}
								{/*{getFieldDecorator('ext_receiverWxName', {*/}
									{/*initialValue: ext.receiverWxName*/}
								{/*})(<Input placeholder="请输入缴费微信实名" />)}*/}
							{/*</FormItem></Col>*/}
						{/*</Row> : null*/}
				{/*}*/}
			</Form>
		);
	}
}

const baseForm = Form.create()(BaseForm);

baseForm.prototype.getValue = function () {
	const { item = {} } = this.props;
	const valueObj = this.getFieldsValue();
	item.id ? valueObj.id = item.id : null;
	const ext = {};
	const extKey = 'ext_';
	for (const k in valueObj) {
		if (k.indexOf(extKey) === 0) {
			const key = k.replace(extKey, '');
			valueObj[k] ? ext[key] = valueObj[k] : null;
			delete valueObj[k];
		}
	}
	valueObj.ext = ext;
	valueObj.roleIds ? valueObj.roleIds = [valueObj.roleIds] : null;
	if (item.password === valueObj.password) delete valueObj.password;
	return valueObj;
};

export default baseForm;
